package com.yuwei.live.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.CountDownTimer
import android.view.Gravity
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.WindowManager
import android.view.animation.LinearInterpolator
import android.widget.*
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ViewCacheExtension
import androidx.recyclerview.widget.SimpleItemAnimator
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.LogUtils.A
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.google.android.gms.dynamite.DynamiteModule.VersionPolicy.IVersions
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.enums.PopupPosition
import com.yuwei.base.RoutePath
import com.yuwei.common.mvi.BaseMviFragment
import com.yuwei.common.mvi.UiState
import com.yuwei.live.LiveIntent
import com.yuwei.live.LiveViewModel
import com.yuwei.live.R
import com.yuwei.live.adapter.RankingAdapter
import com.yuwei.live.cache.LiveItemCache
import com.yuwei.live.databinding.FragmentCommerceRankingBinding
import java.text.SimpleDateFormat
import java.util.*


class CommerceRankingFragment : BaseMviFragment<FragmentCommerceRankingBinding,LiveViewModel>() {
    private val rankingAdapter = RankingAdapter()
    lateinit var countDownTimer : CountDownTimer
    override fun successData(it: UiState.onSuccess<*>) {
        when(it.type){
            "getRankingList" -> {
                val data = it.data as com.yuwei.live.entity.RankingEntity
                rankingAdapter.data.addAll(data)
                rankingAdapter.notifyDataSetChanged()
            }
        }
    }

    override fun failureData(error: String) {

    }

    override fun initView() {
        vm.sendIntent(LiveIntent.getRankingList)
        binding.rankingRv.adapter = rankingAdapter
        binding.rankingRv.layoutManager = LinearLayoutManager(requireContext())
        val inflate = LayoutInflater.from(requireContext()).inflate(R.layout.rule_layout, null)
        val popupWindow = PopupWindow(
            inflate,
            ViewGroup.LayoutParams.MATCH_PARENT,
            900
        )
        popupWindow.isFocusable = true
        binding.rule.setOnClickListener {
            popupWindow.contentView.translationX = 900f // 下滑距离（根据需求调整
            popupWindow.contentView.animate()
                .translationX(0f)
                .setInterpolator(LinearInterpolator())
                .setDuration(500)
                .start()
            popupWindow.showAsDropDown(
                binding.parentLayout,
                Gravity.BOTTOM,
                0,
                0,
            )
        }
        val back = inflate.findViewById<ImageView>(R.id.rule_back)
        back.setOnClickListener {
            popupWindow.dismiss()
        }
    }

    override fun initData() {
        binding.rankingRv.run {
            setItemViewCacheSize(15)//设置屏幕外的缓存数量，默认为2
            setHasFixedSize(true) //减少固定大小的组件反复测量
            setRecycledViewPool(RecyclerView.RecycledViewPool().apply {
                setMaxRecycledViews(0,10) //根据不同的组件类型缓存
            })
            setViewCacheExtension(LiveItemCache())
            //滚动时停止图片加载
            addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    super.onScrollStateChanged(recyclerView, newState)
                    if(newState == RecyclerView.SCROLL_STATE_IDLE){
                        Glide.with(this@CommerceRankingFragment).resumeRequests()
                    }
                    if(newState == RecyclerView.SCROLL_STATE_DRAGGING){
                        Glide.with(this@CommerceRankingFragment).pauseRequests()
                    }
                }
            })
            //关闭不必要的动画
            val animator = itemAnimator as SimpleItemAnimator
            animator.supportsChangeAnimations = false
        }
        rankingAdapter.setOnItemClickListener { _, _, position ->
            XPopup.Builder(requireContext())
                .autoDismiss(false) // 点击按钮不自动关闭
                .hasShadowBg(true) // 显示半透明背景
                .asConfirm(
                    null,
                    "确定要跳转到 ${rankingAdapter.data[position].room_name} 的直播间么?",
                    "取消", // 确认按钮文本
                    "确定不再提醒",  // 取消按钮文本
                    {
                        // 确认回调
                        ToastUtils.showShort("确定跳转")
                    },
                    {
                        // 取消回调
                        ToastUtils.showShort("取消跳转")
                    },
                    false, // 是否隐藏取消按钮
                )
                .show()
        }
    }
    override fun onResume() {
        super.onResume()
        val calendar = Calendar.getInstance()
        val currentMinute = calendar.get(Calendar.MINUTE)
        val currentSecond = calendar.get(Calendar.SECOND)
        countDownTimer = object : CountDownTimer((3600 - (currentMinute * 60 + currentSecond))* 1000.toLong(), 1000) {
            override fun onTick(millisUntilFinished: Long) {
                val sdf = SimpleDateFormat("mm:ss")
                binding.countdownTime.text = "倒计时 ${sdf.format(millisUntilFinished)}"
            }

            override fun onFinish() {

            }
        }.start()

    }

    override fun onPause() {
        super.onPause()
        countDownTimer.cancel()
    }

}